import React, { Component } from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import PropTypes from 'prop-types';
import { Avatar, Input, Menu, Icon, Badge, Row, Col, Dropdown,Tag} from 'antd';

import SidebarAPI from '../../../api/sidebar/index';
import AuthApi from '../../../api/auth/index';
import changeMenu from '../../../actions/menu';
import './Sidebar.scss';
import {TASK_NEW,TASK_OPEN,TASK_CLOSE} from '../../../constants/ActionTypes'
import {observer} from "mobx-react";
import { observable, action, computed ,autorun} from "mobx";
import {taskList} from '../../../store/index';
const { Search } = Input;
const MenuItemGroup = Menu.ItemGroup;
var currentHwnd=null;

class Sidebar extends Component {
  state = {
    tasks: [],
    apps:[],
    index:0,
    account: window.sessionStorage.getItem('account'),
    unreadCount: 0,
  }
  constructor(){
    super()
    autorun(()=>{

     this.setState({tasks:taskList.list,index:taskList.index})
    })
  }
  async getAppList() {
    const response = await SidebarAPI.getAppList();
    const { code, data } = response;
    data.push({
      deleted:false,
      icon:"icon-office",
      id:"manage",
      method:"manage",
      nickname:"主体管理",
      sequence:1,
      url:"/manage",
    }, {
      deleted:false,
      icon:"icon-user",
      id:"userManage",
      method:"userManage",
      nickname:"员工管理",
      sequence:1,
      url:"/userManage",
    });
    if (code === 1) {
      this.setState({
        apps: data,
      });
    } else {
      // message.error('应用列表获取失败，请重试!');
    }
  }
  async getUnreadCount() {
    const response = await SidebarAPI.getUnreadCount();
    const { code, data } = response;
    if (code === 1) {
      this.setState({ unreadCount: data });
    } else {
      // message.error('未读信息数量获取失败，请重试');
    }
  }
  handleClickMenu = (selectedMenu) => {
    const { key } = selectedMenu;
    switch (key) {
      case 'office':
        window.open('/loadingOffice');
        break;
      case 'calendar':
        window.open('/loadingCalendar');
        break;
      case 'doc_view':
        window.open('/loadingDocView');
        break;
      default:
        this.props.changeMenu(key);
        break;
    }
  }
componentWillReceiveProps = (nextProps) => {
  console.log(nextProps)
//  var tasks=this.state.tasks
  // if(currentHwnd!=nextProps.task.hwnd){
  //   currentHwnd=nextProps.task.hwnd
  //   switch(nextProps.task.event){
  //   case TASK_NEW:
  //   tasks.push(nextProps.task)
  //   this.setState({task:tasks})
  //   break;
  // }
//}

};

  componentDidMount() {
    this.getAppList();
    this.getUnreadCount();
  }
  accountCenter() {
    this.props.changeMenu('accountCenter');
  }
  async logout() {
    const response = await AuthApi.logout();
    const { code } = response;
    if (code === 1) {
      window.sessionStorage.removeItem('account');
      window.localStorage.removeItem('accessToken');
      window.localStorage.removeItem('refreshToken');
      this.props.logout();
    } else {
      // message.error('操作失败');
    }
  }
  onChangeDropdown = ({ key }) => {
    this[key].call(this);
  }
  // 点击显示消息信息页面
  handleClickBadge = () => {
    window.open('/loading');
  }
  onTaskClose=()=>{



  }
  render() {
    const account = JSON.parse(this.state.account);
    let { avatar } = account;
    avatar = `${avatar}&imageView2/1/w/80/h/80`;
    const menu = (
      <Menu onClick={this.onChangeDropdown} style={{ width: 220, left: 14 }}>
        <MenuItemGroup key="g1" title="账户">
          <Menu.Item key="accountCenter"><Icon type="user" style={{ marginRight: 10, lineHeight: '30px' }} />个人中心</Menu.Item>
          <Menu.Item key="logout"><Icon type="logout" style={{ marginRight: 10, lineHeight: '30px' }} />退出登录</Menu.Item>
        </MenuItemGroup>
      </Menu>
    );
    return (
      <div className="sidebar-view">

        <Row className="logo" type="flex" justify="space-start" align="middle">
          <Dropdown overlay={menu} trigger={['click']}>
            <Col span={18}>
              <Col span={10}>
                <Avatar
                  src={avatar}
                  style={{
                    width: 50, height: 50, borderRadius: '50%', marginLeft: 20,
                  }}
                />
              </Col>
              <Col span={14}>
                <p>{account.nickname}</p>
                <p>
                  <Badge status="success" />
                  <span>在线</span>
                </p>
              </Col>
            </Col>
          </Dropdown>
          <Col span={6}>
            <Badge count={this.state.unreadCount} onClick={this.handleClickBadge}>
              <Icon type="mail" style={{ fontSize: 26 }} />
            </Badge>
          </Col>
        </Row>

        <div className="search-wrapper">
          <Search
            placeholder=""
            style={{ width: 215 }}
          />
        </div>
        <Menu
          mode="inline"
          style={{ width: 248, border: 0 }}
          onClick={this.handleClickMenu}
        >
          <Menu.Item key="home" id="home"><Icon type="home" />主页</Menu.Item>
          {/* <Menu.Item key="app" id="app"><Icon type="cloud-o" />应用</Menu.Item> */}
          {
            this.state.apps.map(item => (
              <Menu.Item key={item.id}><Icon type="home" />{item.nickname}</Menu.Item>
            ))
          }
        </Menu>
        <div>
        {
           this.state.tasks.map(item=>(
            <Tag key={item.uuid} closable style={{display:"block",marginLeft:20,marginTop:10,width:100}} onClose={this.onTaskClose}><Icon type="home" style={{marginRight:5,border:"none",background:"#fff"}} />{item.name}</Tag>
           ))

        }
        </div>
        </div>
    );
  }
}

Sidebar.propTypes = {
  changeMenu: PropTypes.func.isRequired,
  logout: PropTypes.func.isRequired,
};

const mapDispatchToProps = dispatch => ({
  changeMenu: selectedMenu => dispatch(changeMenu(selectedMenu)),
  logout: () => dispatch(push('/')),
});

export default connect(state => state, mapDispatchToProps)(Sidebar);
